//
//  PhotoListView.m
//  CToolBox
//
//  Created by crj on 16/8/29.
//  Copyright © 2016年 oyf. All rights reserved.
//

#import "PhotoListView.h"
#import "UIButton+WebCache.h"
#import "MLPhotoBrowserSignleViewController.h"
NSInteger const maxCount = 9;//总的最多显示数
NSInteger const maxCountForSection = 3;//每行最多item数

CGFloat const spaceH = 18;//水平面间距
CGFloat const spaceV = 20;//垂直线间距


@interface PhotoListView()

@property (nonatomic, strong) NSArray *dataSource;

@end

@implementation PhotoListView

- (instancetype)initWithDataArray:(NSArray *)dataArray frame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = dataArray;
        [self setUIWithFrame:frame];
    }
    return self;
}

- (void)setUIWithFrame:(CGRect)rect{
    
    NSInteger row =0;
    NSInteger section =0;
    for(int i=0; i<_dataSource.count; i++){
        
        NSString *urlStr = _dataSource[i];
        
        CGFloat itemWidth = [PhotoListView itemWidthWithViewWidth:rect.size.width];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        button.imageView.contentMode = UIViewContentModeScaleAspectFill;

        button.frame = CGRectMake(row*(itemWidth+spaceV), section*(itemWidth +spaceH), itemWidth, itemWidth);
        [button addTarget:self action:@selector(itemDidSelect:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        [button setBackgroundColor:[UIColor redColor]];
        [button sd_setImageWithURL:[NSURL URLWithString:urlStr] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:kDefaultImage]];
        row++;
        if(row==3){
            row=0;
            section++;
        }
        if(i>=maxCount-1){
            break;
        }
    }
}

- (void)itemDidSelect:(UIButton *)btn{
    
    NSLog(@"select %zi",btn.tag);
    NSString *urlStr = _dataSource[btn.tag];
    MLPhotoBrowserSignleViewController *photoVC = [[MLPhotoBrowserSignleViewController alloc] init];
    [photoVC showHeadPortrait:btn.imageView originUrl:urlStr];
}

//需要的总体高度
+ (CGFloat)heightWithImageCount:(NSInteger)imageCount viewWidth:(CGFloat)viewWidth{
    
   
    CGFloat itemWidth = [self itemWidthWithViewWidth:viewWidth];
    
    
    NSInteger sections = [self sectionsWithImageCount:imageCount];
    
    CGFloat height = (itemWidth+spaceV)*sections;
    
    return height;
}
//需要的行数
+ (NSInteger)sectionsWithImageCount:(NSInteger)imageCount{
    
    NSInteger section = 0;
    imageCount = imageCount<maxCount?imageCount:maxCount;
    section = (imageCount-1)/maxCountForSection+1;
    return section;
}

//item宽度
+ (CGFloat)itemWidthWithViewWidth:(CGFloat)viewWidth{
    
    CGFloat itemWidth =  (viewWidth-spaceH*maxCountForSection)/maxCountForSection;
    return itemWidth;
}

@end
